
import { getUniqueFileName, getMd5 } from '../../utils/fileUtils'
import qiniuUpload from './image-uploader'
import http from '@/utils/httpRequest'

export default class UploadFile {
  constructor(file, token, domain, withCompressVideo) {
    this.file = file
    this.token = token
    this.domain = domain
    this.originFileName = file.name
    this.uniqueFileName = getUniqueFileName(file.name)
    this.withCompressVideo = withCompressVideo || false
  }

  upload({ onProcess, onSuccess, onError }) {
    var observer = this.createObserver(onProcess, onSuccess, onError)
    qiniuUpload(this.file, this.uniqueFileName, this.token, observer)
  }

  createObserver(onProcess, onSuccess, onError) {
    return {
      next: res => {
        var process = parseInt(res.total.percent)
        typeof onProcess === 'function' && onProcess(process)
      },
      error: err => {
        typeof onError === 'function' && onError(err)
      },
      complete: res => {
        var key = res.key
        if (this.withCompressVideo) {
          console.log(key)
          if (!key.endsWith('.mp4')) {
            console.log('use_mp4_720')
            key = 'mp4_720p_' + key.replace('.flv', '.mp4').replace('.mpeg', '.mp4')
          }
        }
        let sourceLink = this.domain + '/' + key
        typeof onSuccess === 'function' && onSuccess({
          name: this.originFileName,
          url: sourceLink
        })
      }
    }
  }

  async getUrlByFileMd5() {
    const md5 = await getMd5(this.file)
    let res = await http.post('/sys/oss/getUrlByMd5', {
      fileMd5: md5
    })
    return res.data ? res.data : null
  }

  async saveFileMd5() {
    const md5 = await getMd5(this.file)
    await http.post('/sys/oss/saveUrlByMd5', {
      fileMd5: md5,
      fileName: this.uniqueFileName,
      url: this.url
    })
  }
}
